import os
import uuid
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser
from rest_framework import status
from django.core.files.storage import default_storage
from django.conf import settings


class FileUploadView(APIView):
    authentication_classes = []
    permission_classes = []
    parser_classes = [MultiPartParser]

    def post(self, request, *args, **kwargs):
        file_obj = request.data['file']
        unique_filename = str(uuid.uuid4())
        file_name, file_extension = os.path.splitext(file_obj.name)
        new_file_name = f"{unique_filename}{file_extension}"

        file_path = os.path.join(settings.MEDIA_ROOT, new_file_name)
        with default_storage.open(file_path, 'wb+') as destination:
            for chunk in file_obj.chunks():
                destination.write(chunk)
        file_url = f'{settings.HOST}{settings.MEDIA_URL}{new_file_name}'
        res = {
            'url': file_url
        }
        return Response(res, status=status.HTTP_201_CREATED)
